#include "head.h"

int net_gets(int socket_fd, thread_status *t_status){
    printf("进入gets\n");

    //thread_status *t_status = (thread_status *)p;
    request_t request = *t_status->request;
    
    /*char ip[100] = {0};
    load_config("ip", ip);
    char port[100] = {0};
    load_config("port", port);

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    pthread_cleanup_push(cleanup_socket, &socket_fd);

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);

    connect(socket_fd, (struct sockaddr *)&addr, sizeof(addr));
*/
    // 发送请求报文
    send(socket_fd, &request , sizeof(request_t), 0);

    // 等待响应
    response_t res;
    bzero(&res, sizeof(res));
    recv(socket_fd, &res, sizeof(res), 0);
    if(res.status == 3){
        // 重连失败
        return 3;
    }
    if(res.status == 1){
        // 异常返回
        puts(res.args);
        return -1;
    }
    printf("---响应报文---\n");
    printf("status: %d\n",res.status);
    printf("args: %s\n",res.args);
    printf("-------------\n");
    // 接收文件
    recv_file(request.args, socket_fd);

    //pthread_cleanup_pop(1);

    pthread_mutex_lock(&t_status->lock);
    int i = 0;
    pthread_t tid = pthread_self();
    for(i = 0; i < t_status->length; i++){
        if(tid == t_status->thread_ids[i]){
            break;
        }
    }
    t_status->status[i] = 0;
    pthread_mutex_unlock(&t_status->lock);
    // 释放临时request
    free(t_status->request);
    return 0;
}

